const CAS = 'http://localhost:8080';
const BACKEND = 'http://localhost:8082';
const PARAMS = new URLSearchParams(window.location.search);
const STUDENT_PER_PAGE = 10;
const BUTTONS_PER_PAGE = 5;
let currentPage = 1;  
  
// 辅助函数，用于创建并绑定页码按钮  
function createPaginationButton(pageNumber, isActive) {  
    const button = document.createElement('button');  
    button.textContent = pageNumber;  
    button.classList.add('pagination-button');  
    if (isActive) {  
        button.classList.add('active');  
    }  
    button.onclick = () => {
		currentPage = pageNumber;
		showPage();
	};  
    return button;  
}  
  
// 展示分页按钮的函数  
function showPaginationButtons(totalPages) {  
    const pagination = document.querySelector('.pagination');  
    pagination.innerHTML = '';  
	
    // 计算要显示的页码范围  
    let startPage;
	let endPage;
	if (totalPages < BUTTONS_PER_PAGE) {
		startPage = 1;
		endPage = totalPages;
	} else {
		if (currentPage - Math.floor(BUTTONS_PER_PAGE / 2) < 1) {
			startPage = 1;
			endPage = BUTTONS_PER_PAGE;
		} else if (currentPage + Math.floor(BUTTONS_PER_PAGE / 2) > totalPages) {
			startPage = totalPages - BUTTONS_PER_PAGE + 1;
			endPage = totalPages;
		} else {
			startPage = currentPage - Math.floor(BUTTONS_PER_PAGE / 2);
			endPage = currentPage + Math.floor(BUTTONS_PER_PAGE / 2);
		}
	}

    // 添加页码按钮  
    for (let i = startPage; i <= endPage; i++) {  
        pagination.appendChild(createPaginationButton(i, i === currentPage));  
    }  

}  

// 加载学生列表
function renderStudents(pageStudents) {
	// 清空学生列表  
	const studentList = document.querySelector('.student-list');  
	studentList.innerHTML = '';  
  
	// 显示当前页的学生  
	pageStudents.forEach((student, index) => {  
		// 创建学生的div元素  
		const item = document.createElement('div');    
		item.className = 'student-item';    
  
		// 创建学生的摘要信息
		const header = document.createElement('div');  
		header.className = 'student-header';
		header.onclick = toggle;
		const digest = document.createElement('h4');
		digest.textContent = `${student.id}`;
		const open = document.createElement('span');
		open.className = 'toggle-btn';
		open.textContent = '...';
		header.appendChild(digest);
		header.appendChild(open);
		  
		// 创建学生的详细信息
		const details = document.createElement('div');
		details.className = 'student-details';
		// 创建修改按钮  
		const p = document.createElement('p');
		p.innerHTML = `<span>学号:</span> <input value="${student.id}" readonly/>`;
		const p1 = document.createElement('p');
		p1.innerHTML = `<span>姓名:</span> <input value="${student.name}"/>`;
		const p2 = document.createElement('p');
		p2.innerHTML = `<span>性别:</span> <input value="${student.sex}"/>`;
		const tail = document.createElement('h3');
		const deleteBtn = document.createElement('button');
		const editBtn = document.createElement('button');  
		editBtn.textContent = '修改';  
		editBtn.onclick = updateStudent;
		deleteBtn.textContent = '删除';
		deleteBtn.onclick = deleteStudent;
		tail.appendChild(editBtn);
		tail.appendChild(deleteBtn);
		details.appendChild(p);
		details.appendChild(p1);
		details.appendChild(p2);
		details.appendChild(tail);
  
		// 将学生的信息文本和两个按钮添加到学生的div元素中  
		item.appendChild(header);  
		item.appendChild(details);
  
		// 将学生的div元素添加到学生列表中  
		studentList.appendChild(item);    
	});  
}

function fetchPage() {
	const apiUrl = `${BACKEND}/admin/student/${STUDENT_PER_PAGE}/${currentPage}`;
	return fetch(apiUrl, {
		credentials: "include"
	})  
	    .then(response => {  
	        if (!response.ok) {  
	            throw new Error('Failed to fetch classes');  
	        }  
	        return response.json();  
	    })  
	    .catch(error => {  
	        console.error('Error fetching classes:', error);  
	    });  
}

function showPage() {
	const total = document.getElementById('total');
	fetchPage().then(data=>{
		total.textContent = `共${data.totalPages}页 ${data.totalElements}名学生`;
		renderStudents(data.students);
		showPaginationButtons(data.totalPages);
	});
}
  
showPage(1);

// 展开或折叠学生
function toggle(event) {
	const details = event.target.parentNode.nextElementSibling;  
	if (details.style.maxHeight) {  
		// 如果已经展开，则折叠  
		details.style.maxHeight = null;  
		details.classList.remove('expanded');  
	} else {  
		// 如果已经折叠，则展开  
		details.style.maxHeight = '500px'; // 或者使用CSS变量来控制  
		details.classList.add('expanded');  
	}  
}

// 创建学生
function createStudent(event) {
	
}

// 修改学生
function updateStudent(event) {
	const details = event.target.parentNode.parentNode;
	const idInput = details.querySelector('.student-details p:nth-child(1) input');  
	const nameInput = details.querySelector('.student-details p:nth-child(2) input');  
	const sexInput = details.querySelector('.student-details p:nth-child(3) input');  
	const id = idInput.value;  
	const name = nameInput.value;  
	const sex = sexInput.value;  
	const apiUrl = `${BACKEND}/admin/student/${id}`;
	const data = {
		id,
		name,
		sex
	};
	fetch(apiUrl, {
		method: 'POST',
		credentials: "include",
		headers: {  
			'Content-Type': 'application/json'
		},  
		body: JSON.stringify(data)  
	})  
	.then(response => {  
		if (!response.ok) {  
			throw new Error('Failed to fetch classes');  
		}
		alert("更新成功");
	})  
	.catch(error => {  
		console.error('Error fetching classes:', error);  
	});  
}

// 删除学生
function deleteStudent(event) {
	const details = event.target.parentNode.parentNode;  
	const idInput = details.querySelector('.student-details p:nth-child(1) input');  
	const id = idInput.value;  
	const apiUrl = `${BACKEND}/admin/student/${id}`;
	fetch(apiUrl, {  
		method: 'DELETE',  
		credentials: "include"
	})  
	.then(response => {  
		if (!response.ok) {  
			throw new Error('Failed to fetch classes');  
		}
		const studentItem = details.parentNode;
		studentItem.remove();
	})  
	.catch(error => {  
		console.error('Error fetching classes:', error);  
	});  
}

// 获取模态对话框和触发按钮  
const modal = document.getElementById('studentModal');  
const btn = document.getElementById('createBtn');  
const span = document.getElementsByClassName("close")[0];  
const form = document.getElementById('studentForm');  
  
// 显示模态对话框  
btn.onclick = function() {  
  modal.style.display = "block";  
}  
  
// 隐藏模态对话框  
span.onclick = function() {  
  modal.style.display = "none";  
}  
  
// 阻止表单默认提交行为，改为使用AJAX发送数据  
form.addEventListener('submit', function(event) {  
  event.preventDefault(); // 阻止表单的默认提交行为  
  
  // 获取表单中的值  
  const name = document.getElementById('name').value;  
  const id = document.getElementById('id').value;  
  const sex = document.getElementById('sex').value;  
  
  // 验证表单数据（这里只是简单的非空验证，你可能需要更复杂的验证）  
  if (name && id && sex) {  
    // 使用fetch API发送POST请求到服务器  
    const apiUrl = `${BACKEND}/admin/student/${id}`; // 假设的API地址  
    const data = { name, id, sex }; // 将表单数据转换为JSON对象  
  
    fetch(apiUrl, {  
      method: 'PUT',
	  credentials: "include",
      headers: {  
        'Content-Type': 'application/json',  
      },  
      body: JSON.stringify(data) // 将JSON对象转换为JSON字符串  
    })  
    .then(response => {  
      if (!response.ok) {  
        throw new Error('Failed to create student');  
      }  
      // 如果服务器响应成功，可以关闭模态对话框并显示成功消息  
      modal.style.display = "none";  
      showPage();
    })  
    .catch(error => {  
      console.error('Error creating student:', error);  
      // 在这里可以显示错误消息给用户  
      alert('创建学生时出错：' + error.message);  
    });  
  } else {  
    // 如果没有填写所有必填字段，显示错误消息  
    alert('请填写所有必填字段！');  
  }  
});  
  
// 当用户点击模态对话框以外的地方时，关闭它（如果点击的不是模态对话框的内容）  
window.onclick = function(event) {  
  if (event.target === modal) {  
    modal.style.display = "none";  
  }  
};

const logoutBtn = document.getElementById('logoutBtn');
logoutBtn.addEventListener('click', ()=>{
	window.location.href = `${CAS}/logout-page`;
	localStorage.setItem('account', null);
	localStorage.setItem('token', null);
});
